#include "parser.h"
#include "daemon.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#define MAX_LINE_LENGTH 1024

int parser_is_valid_dir(const char *path) {
  struct stat s;
  stat(path, &s);

  return S_ISDIR(s.st_mode);
}

daemon_t *parser_load_daemon_from_file(const char *path) {
  daemon_t *new = (daemon_t *)malloc(sizeof(daemon_t));

  FILE *file = fopen(path, "r");
  if (file == NULL)
    return NULL;
  char line[MAX_LINE_LENGTH];

  // TODO: Probably refactor this Ctrl+C/V crap
  // Daemon name
  if (fgets(line, MAX_LINE_LENGTH, file) == NULL)
    return NULL;
  line[strcspn(line, "\r\n")] = 0;
  new->name = (char *)malloc(sizeof(char) * strlen(line) + 1);
  strcpy(new->name, line);
  memset(line, 0, MAX_LINE_LENGTH);

  // Daemon deps
  if (fgets(line, MAX_LINE_LENGTH, file) == NULL)
    return NULL;
  line[strcspn(line, "\r\n")] = 0;
  new->deps = (char *)malloc(sizeof(char) * strlen(line) + 1);
  strcpy(new->deps, line);
  memset(line, 0, MAX_LINE_LENGTH);

  // Daemon launch command
  if (fgets(line, MAX_LINE_LENGTH, file) == NULL)
    return NULL;
  line[strcspn(line, "\r\n")] = 0;
  new->launch_command = (char *)malloc(sizeof(char) * strlen(line) + 1);
  strcpy(new->launch_command, line);

  fclose(file);
  return new;
}